import Vue from "vue";
import VueRouter from "vue-router";
import Home from "views/Home.vue";

import QuestionnaireList from "components/home/QuestionnaireList.vue";
import Data from "components/home/Data.vue";
import EvaUser from "components/home/EvaUser.vue";
import ModifyWeight from "components/home/ModifyWeight.vue";
import SingleTableStatistics from "components/home/SingleTableStatistics.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
    children: [
      {
        path: "/",
        redirect: "/questionnaireList"
      },
      {
        path: "/questionnaireList",
        component: QuestionnaireList
      },
      {
        path: "/data",
        component: Data
      },
      {
        path: "/evaUser",
        component: EvaUser
      },
      {
        path: "/modifyWeight",
        component: ModifyWeight
      },
      {
        path: "/questionnaireList/singleTableStatistics/:id/:flag",
        component: SingleTableStatistics
      }
    ]
  },
  {
    path: "/login",
    name: "Login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ "views/Login.vue")
  }
];

const router = new VueRouter({
  // mode: "history",
  base: process.env.BASE_URL,
  routes,
  // 关闭浏览器前进后退功能
  scrollBehavior: () => {
    history.pushState(null, null, document.URL);
  }
});

router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳过来的
  // next 是一个函数 ，表示放行

  // 用户访问的是login页面 ， 直接放行
  if (to.path === "/login") return next();

  // 用户访问home页面时 获取 token 判断是否存在token 若存在则放行
  const tokenStr = window.sessionStorage.getItem("token");
  if (!tokenStr) return next("/login");
  next();
});

export default router;
